package com.cloud.apis.approval.service.impl;


import com.cloud.apis.approval.db.dao.ApprovalMapper;
import com.cloud.apis.approval.pojo.form.*;
import com.cloud.apis.approval.pojo.vo.ApprovalInfoVo;
import com.cloud.apis.approval.pojo.vo.ApprovalVo;
import com.cloud.apis.approval.service.IApprovalService;
import com.cloud.apis.core.exception.CustomException;
import com.cloud.apis.core.model.Dict;
import com.cloud.apis.core.model.PageData;
import com.cloud.apis.core.utils.PageInfoToPageDataConverterUtil;
import com.cloud.apis.core.web.ServiceCode;
import com.cloud.apis.dict.db.dao.DictMapper;
import com.cloud.apis.message.task.MessageTask;
import com.cloud.apis.message.utils.MessageSendUtil;
import com.cloud.apis.user.db.dao.UserMapper;
import com.cloud.apis.user.pojo.vo.UserInfoVo;
import com.cloud.apis.websocket.WebSocketServe;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * 审批模块业务实现
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/4/6
 */
@Slf4j
@Service
public class ApprovalService implements IApprovalService {
    @Autowired
    private ApprovalMapper approvalMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageTask messageTask;
    @Autowired
    private WebSocketServe webSocketServe;
    @Value("${custom-config.default-query-page-size}")
    private Integer defaultQueryPageSize;

    public ApprovalService(){
        log.info("【ApprovalService】");
    }

    @Override
    public ArrayList<ApprovalInfoVo> searchApprovalByApplyIdAndApprovalType(Long applyId, String approvalType) {
        Dict dict = dictMapper.selectDictByAbbreviation(approvalType);
        if (dict == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "审批类型不存在");
        }
        return approvalMapper.searchApprovalByApplyIdAndApprovalType(applyId, dict.getId());
    }

    @Override
    public ApprovalInfoVo applyApprovalService(ApplyApprovalForm form) {
        UserInfoVo applyUser = userMapper.selectUserById(form.getApplyId());
        UserInfoVo approvalUser = userMapper.selectUserById(form.getApprovalId());
        if (applyUser == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "用户不存在");
        }
        if (approvalUser == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "审批人不存在,请重新选择");
        }
        if (applyUser.getOrganization() == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "用户所在部门不存在");
        }
        //根据申请的审批类型查询对应的审批类型字典
        Dict dict = dictMapper.selectDictByAbbreviation(form.getApprovalType());
        if (dict == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "审批类型不存在");
        }
        //发送消息给审批者
        String approvalMessage =
                "您有一份审批需要处理，该审批为" + dict.getName() +
                        "，申请人为:" + applyUser.getName() +
                        "，申请人岗位:" + applyUser.getJob().getName() +
                        "，申请者电话为:" + applyUser.getAccount() +
                        "，请及时处理。";
        MessageSendUtil.sendSimpleMessage(messageTask, form.getApprovalId(), "系统消息", approvalMessage);
        webSocketServe.sendMessage(form.getApprovalId());
        //发送消息给申请人
        String applyMessage =
                "您的" + dict.getName() +
                        "审批申请已提交给" + approvalUser.getName() +
                        "进行审批，电话号码为" + approvalUser.getAccount() +
                        "，请耐心等待审批结果。";
        MessageSendUtil.sendSimpleMessage(messageTask, applyUser.getId(), "系统消息", applyMessage);
        webSocketServe.sendMessage(applyUser.getId());
        int num = approvalMapper.applyApproval(form, dict.getId());
        if (num < 0) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "提交审批失败");
        }
        Long approvalId = form.getId();
        return approvalMapper.selectApprovalById(approvalId);
    }

    @Override
    public PageData<ApprovalVo> listPage(Integer pageNum, Integer pageSize, ApprovalListForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<ApprovalVo> list = approvalMapper.list(form.getApprovalType(), form.getApprovalStatus());
        PageInfo<ApprovalVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public void updateResult(ApprovalResultForm form)  {
        //根据传递的审批id获取审批的详细信息
        ApprovalInfoVo approval = approvalMapper.selectApprovalById(form.getId());
        if (approval == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "审批不存在");
        }
        //如果审批状态为3，表示审批不通过
        if (form.getApprovalStatus() == 3) {
            String message = "您的" + approval.getApprovalDict().getName() + "审批申请未通过，" +
                    "原因为:" + form.getApprovalReason() +
                    "请重新提交申请！";
            MessageSendUtil.sendSimpleMessage(messageTask, approval.getApplyId(), "系统消息", message);
            webSocketServe.sendMessage(approval.getApplyId());
        } else {
            String message = "您的" + approval.getApprovalDict().getName() + "审批申请已通过，" +
                    "请及时查看！";
            MessageSendUtil.sendSimpleMessage(messageTask, approval.getApplyId(), "系统消息",message);
            webSocketServe.sendMessage(approval.getApplyId());
        }
        int num = approvalMapper.updateByIdAndApprovalStatus(form);
        if (num < 0) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "审批失败");
        }
    }

    @Override
    public void updateCut(SetCutForm form) {
        ApprovalInfoVo approval = approvalMapper.selectApprovalById(form.getId());
        if (approval == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "审批不存在");
        }
        int num = approvalMapper.updateCutById(form);
        MessageSendUtil.sendSimpleMessage(messageTask, approval.getApplyId(), "系统消息", "您的入职审批已经变为重新登记或撤销状态，请及时查看");
        webSocketServe.sendMessage(approval.getApplyId());
        if (num < 0) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "撤销失败");
        }
    }

    @Override
    public PageData<ApprovalVo> getListByApprovalId(ApprovalIdForm form) {
        return listPageByApprovalId(form.getPageNum(), defaultQueryPageSize, form);
    }

    @Override
    public PageData<ApprovalVo> listPageByApprovalId(Integer pageNum, Integer pageSize, ApprovalIdForm form) {
        PageHelper.startPage(pageNum, pageSize);
        //根据审批者id查询其下的所有审批列表
        List<ApprovalVo> list = approvalMapper.listPageByApprovalId(form);
        PageInfo<ApprovalVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public PageData<ApprovalVo> listApproval(ApprovalListForm form) {
        return listPage(form.getPageNum(), defaultQueryPageSize, form);
    }
}
